package com.ds.infrastructure.audit.common.entity;

import lombok.Data;
import lombok.ToString;

import javax.validation.constraints.NotBlank;
import java.io.*;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/8/4
 */
@Data
@ToString(callSuper = true)
public class KbaBehaviorWrapper extends KbaBehavior {

    private static final long serialVersionUID = -9097485052820194172L;

    @NotBlank(message = "appName不能为空")
    private String appName;

    @NotBlank(message = "appKey不能为空")
    private String appKey;


    public static KbaBehaviorWrapper of(KbaBehavior behavior) {
        KbaBehaviorWrapper wrapper = new KbaBehaviorWrapper();
        wrapper.setGroupId(behavior.getGroupId());
        wrapper.setShopId(behavior.getShopId());
        wrapper.setBizName(behavior.getBizName());
        wrapper.setBehaviorId(behavior.getBehaviorId());
        wrapper.setAction(behavior.getAction());
        wrapper.setActionDetail(behavior.getActionDetail());
        wrapper.setPriority(behavior.getPriority());
        wrapper.setUserId(behavior.getUserId());
        wrapper.setExtra(behavior.getExtra());
        wrapper.setCreateTime(behavior.getCreateTime());
        return wrapper;
    }

    public byte[] toBytes() {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(bo);
            oos.writeObject(this);
            oos.flush();
            oos.close();
            bo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bo.toByteArray();
    }

    public static KbaBehaviorWrapper toWrapper(byte[] bytes) {
        KbaBehaviorWrapper wrapper = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            wrapper = (KbaBehaviorWrapper) ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException | ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return wrapper;
    }
}
